package bitetorrent.peersComm;

import bitetorrent.helper.Converter;
import bitetorrent.model.Global;
import java.io.IOException;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author user
 */
public class P2PServer extends P2P {

    public P2PServer(Socket sock) throws IOException {
        super(sock);
        type = "server";
    }

    @Override
    public void run() {
        try {
            if (recieveHandshake()) {
                try {
                    // Handshake is recieved
                    System.out.println("Handshake diterima :).");
                    recieveMessage();
                } catch (InterruptedException ex) {
                    Logger.getLogger(P2PServer.class.getName()).log(Level.SEVERE, null, ex);
                }
            } else {
                // Close connection
                sock.close();
            }
        } catch (IOException ex) {
            Logger.getLogger(P2PServer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private boolean recieveHandshake() {
        byte[] bytesPstrLen = new byte[4];
        byte[] bytesPstr;
        byte[] bytesInfoHash;
        int pstrLen;
        int i = 0;
        String pstr;

        try {
            // Read pstrlen
            in.read(bytesPstrLen);
            pstrLen = Converter.bytesToInt(bytesPstrLen);
            System.out.println("Panjang nama protokol : " + pstrLen);

            // Read pstr
            bytesPstr = new byte[pstrLen];
            while (i < pstrLen) {
                bytesPstr[i] = (byte) in.read();
                ++i;
            }
            pstr = Converter.bytesToString(bytesPstr);
            System.out.println("Nama protokol : " + pstr);

            // Chek pstr
            if (pstr.equals("BitTorrent protocol")) {
                // Read reserved, Skip read this
                in.skip(8);

                // Read info_hash
                bytesInfoHash = new byte[20];
                in.read(bytesInfoHash);
                infoHash = Converter.bytesToString(bytesInfoHash);
                debug("hash : " + infoHash);

                // Check pieces
                downloader = Global.fileDownloads.find(infoHash);

                if (downloader == null) {
                    System.out.println("Handshake gagal. file tidak ditemukan.");
                    return false;
                } else {
                    byte[] bytesBitField = downloader.getBitField();
                    // Send bit field
                    sendBitField(bytesBitField);
                }
            } else {
                // Fail
                System.out.println("Handshake tidak valid.");
                return false;
            }
        } catch (IOException ex) {
            Logger.getLogger(P2PServer.class.getName()).log(Level.SEVERE, null, ex);
        }

        return true;
    }
}
